<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Core_Model_Mapper_Abstract
 *
 * @author Eugene
 */
abstract class Application_Model_Mapper_Abstract
{

	/**
	 * @var Zend_Db_Table_Abstract
	 */
	protected $_dbTable;

	/**
	 * @var string
	 */
	protected $_dbTableClass;

	/**
	 *
	 * @param mixed $dbTable
	 * @return Zend_Db_Table_Abstract
	 */
	public function setDbTable($dbTable)
	{
		if (is_string($dbTable)) {
			$dbTable = new $dbTable;
		}

		if (!$dbTable instanceof Zend_Db_Table_Abstract) {
			throw new Exception('Invalid table data gateway provided');
		}

		$this->_dbTable = $dbTable;

		return $this;
	}

	/**
	 *
	 * @return Zend_Db_Table_Abstract
	 */
	public function getDbTable()
	{
		if (null === $this->_dbTable) {
			$this->setDbTable($this->_dbTableClass);
		}

		return $this->_dbTable;
	}

	/**
	 * @param Application_Model_Abstract $model
	 * @return void
	 */
	abstract public function save(Application_Model_Abstract $model);

	/**
	 *
	 * @param int $id
	 * @param Application_Model_Abstract $model
	 * @return void
	 */
	public function fetchById($id, Application_Model_Abstract $model)
	{
		$result = $this->getDbTable()->find($id);
		if (0 == count($result)) {
			return;
		}

		$row = $result->current();
		$model->setOptions($row->toArray());
	}

	/**
	 *
	 * @param int $id
	 * @return void
	 */
	public function delete($id)
	{
		$result = $this->getDbTable()->find($id);
		if (0 == count($result)) {
			return;
		}

		$result->current()->delete();
	}

}